package top.zsyle.org.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zsyle.basic.query.BaseQuery;
import top.zsyle.basic.service.impl.BaseServiceImpl;
import top.zsyle.basic.util.MD5Utils;
import top.zsyle.basic.util.PageList;
import top.zsyle.basic.util.StrUtils;
import top.zsyle.org.domain.Employee;
import top.zsyle.org.mapper.EmployeeMapper;
import top.zsyle.org.service.IEmployeeService;
import top.zsyle.system.domain.EmployeeRole;
import top.zsyle.system.mapper.RoleMapper;
import top.zsyle.user.domain.Logininfo;
import top.zsyle.user.mapper.LogininfoMapper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;


    @Override
    public List<Employee> findAllByDeptId(Long id) {

        return employeeMapper.findAllByDeptId(id);
    }

    @Override
    public List<Employee> findAllByShopId(Long shopId) {
        return employeeMapper.findAllByShopId(shopId);
    }

    /**
     * 重写 Emp 新增方法，添加emp时需要同步添加logininfo表
     * 盐值、密码需要加密
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        //设置默认密码：123456
        String salt = StrUtils.getComplexRandomString(32);
        //默认密码：123456
        String password = MD5Utils.encrypByMd5(salt + "123456");
        employee.setSalt(salt);
        employee.setPassword(password);
        //创建logininfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        //管理员 0 用户 1
        logininfo.setType(0);
        //状态: 启动 1 禁用 0
        logininfo.setDisable(1);
        logininfoMapper.add(logininfo);
        //添加员工
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);

        //给该员工绑定角色，即操作t_employee_role表
        employeeMapper.addMiddle(employee.getId(),employee.getRoles());
    }

    /**
     * 重写删除方法
     * 同时变更logininfo表
     * @param id
     */
    @Override
    public void delete(Long id) {
        Employee emp = employeeMapper.findById(id);
        if (null != emp.getLogininfoId()){
            //删除该emp的logininfo表中的登录信息
            logininfoMapper.delete(emp.getLogininfoId());
        }
        super.delete(id);

        //删除中间表t_employee_role
        roleMapper.batchDeleteMiddle(id);
    }

    /**
     * 重写update方法
     * 同时修改logininfo表中的数据
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        Employee empComplete = employeeMapper.findById(employee.getId());
        if (null != empComplete.getLogininfoId()){
            Logininfo logininfo = logininfoMapper.findById(empComplete.getLogininfoId());
            //连id都改了  不能用BeanUtils
//            BeanUtils.copyProperties(employee,logininfo);
            logininfo.setUsername(employee.getUsername());
            logininfo.setPhone(employee.getPhone());
            logininfo.setEmail(employee.getEmail());
//            logininfo.setSalt(employee.getSalt());
//            logininfo.setPassword(employee.getPassword());
            //更新logininfo表中的数据
            logininfoMapper.update(logininfo);
        }
        super.update(employee);

        //更新t_employee_role 中间表
        //（先删除，再添加）= 修改
        roleMapper.batchDeleteMiddle(employee.getId());
        //再添加 中间表
        employeeMapper.addMiddle(employee.getId(),employee.getRoles());
    }


    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        // 去除 keyword的前后空格
        if (!StringUtils.isEmpty(query.getKeyword())) {
            query.setKeyword(query.getKeyword().trim());
        }
        // 查询数量
        Integer count = employeeMapper.queryByCount(query);
        // 查询数据
        List<Employee> ts = employeeMapper.queryByPage(query);
        // 查询角色id集合
        List<Long> eIds = ts.stream().map(Employee::getId).collect(Collectors.toList());
        List<EmployeeRole>  employeeRoles = employeeMapper.findRoleIdsByEIds(eIds);
        // 转成map key：empId value：rolesid集合 List<Long> roseIds
        Map<Long, List<Long>> employeeRolesMap = employeeRoles.stream()
                .collect(Collectors.groupingBy(EmployeeRole::getEmployeeId,
                        Collectors.mapping(EmployeeRole::getRoleId, Collectors.toList())));
        ts.forEach(t->{
            List<Long> rolesId = employeeRolesMap.get(t.getId());
            if (!CollectionUtils.isEmpty(rolesId)){
                t.setRoles(rolesId);
            }
        });

        return new PageList<Employee>(count,ts);
    }
}
